# -*- coding: utf-8 -*-


class Action(object):
    actions = {}

    def do_action(self):
        raise NotImplementedError()


class View(Action):
    _type = None


class AdminForm(View):
    _type = 'form'
    _name = None

    def __init__(self, *args, **kwargs):
        pass

    @property
    def data(self):
        return {}


class AdminTable(View):
    _type = 'table'
    _name = None

    def __init__(self, *args, **kwargs):
        pass

    @property
    def data(self):
        return {}


class AdminMenu(object):
    _name = '菜单'
    _key = 'root'
    children = []
    action = None
    sequence = 100

    def __init__(self):
        self.children = []

    def register_child(self, child):
        self.children.append(child)
        self.children = sorted(self.children, key=lambda c: c.sequence)

    def register_action(self, action_cls):
        self.action = "{}.{}".format(action_cls.__module__, action_cls.__name__)
        return self

    def get_by_path(self, path_key):
        if path_key == self._key:
            return self
        if not path_key:
            return root_menu

        child = None
        key = path_key.split(".")[1]
        for c in self.children:
            if c._key == key:
                child = c

        if child:
            return child.get_by_path(".".join(path_key.split(".")[1:]))
        return None

    def render(self, parent_key=None):
        key = "{}{}".format((parent_key + '.') if parent_key else '', self._key)
        return {
            "name": self._name,
            "key": key,
            "children": [c.render(key) for c in self.children],
            "action": self.action
        }


class AdminUserMenu(AdminMenu):
    _name = '用户'
    _key = 'user'


root_menu = AdminMenu()
root_menu.register_child(AdminUserMenu().register_action(AdminTable))
